﻿using System.Collections.Generic;
using System.Diagnostics;
using System;

namespace Cerulean
{
  public class WebDavObject
  {

    static Dictionary<string, WebDavObject> _byPath = new Dictionary<string, WebDavObject>();

    public static WebDavObject ByPath(string path)
    {
      path = path.Replace('\\', '/');
      return _byPath.ContainsKey(path) ? _byPath[path] : null;
    }

    public string ResourceId { get; private set; }
    public string DisplayName { get; private set; }
    public string Type { get; private set; }
    public Uri ContentUri { get; private set; }
    internal WebDavObject Parent { get; private set; }
    private List<WebDavObject> _children = null;

    public List<WebDavObject> Children
    {
      get
      {
        if (((Type == "Library") || (Type == "Folder")) && (_children == null))
        {
          _children = new List<WebDavObject>();
        }
        return _children;
      }
    }

    public WebDavObject(string title, string resourceId, WebDavObject parent, string type, Uri contentUri = null)
    {
      DisplayName = title;
      ResourceId = resourceId;
      Parent = parent;
      Type = type;
      ContentUri = contentUri;
      _byPath[Path] = this;
      if ((Type == "Library") || (Type == "Folder"))
        SkyDrive.Instance.GetFolderItems(this);
    }

    public string Path
    {
      get
      {
        return (Parent == null) ? string.Format("/{0}", DisplayName) : string.Format("{0}/{1}", Parent.Path, DisplayName);
      }
    }

    public override string ToString()
    {
      return string.Format("{0} on path {1}",Type,Path);
    }

    internal static void Remove(string path)
    {
      path = path.Replace('\\', '/');
      int lastSlashPosition = path.LastIndexOf('/');
      if (lastSlashPosition > 0)
      {
        string parentpath = path.Substring(0, lastSlashPosition);
        if (parentpath.Length > 1 && _byPath.ContainsKey(parentpath))
          _byPath[parentpath].Children.Remove(_byPath[parentpath]);
      }
      _byPath.Remove(path);
    }
  }
}
